//
//  MTAddFriendViewController.swift
//  MT
//
//  Created by ooops on 2020/5/5.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory
import YPNavigationBarTransition

extension MTSearchAddFriendViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return result.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: MTSearchFriendListCell.reuseIdentity(), for: indexPath) as! MTSearchFriendListCell
        let model: MTSearchUserInfoModel = result[indexPath.row]
        cell.model = model
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 64
    }
    
}

class MTSearchAddFriendViewController: BaseViewController {

    var searchController: SKSearchController!
    /// 用户手机号 / 觅颜号
    var userMTorPhoneNumber: String = ""
    /// 好友列表
    var userFriendList: [JMSGUser] = []
    
    var user: JMSGUser?
    
    var result: [MTSearchUserInfoModel] = []
    
    let userProvider: MTProvider = MTProvider<UserCenterApi>()
    
    lazy var tableView: UITableView = {
        let table = UITableView(frame: self.view.bounds, style: .plain)
        table.delegate = self
        table.dataSource = self
        table.register(MTSearchFriendListCell.self, forCellReuseIdentifier: MTSearchFriendListCell.reuseIdentity())
        table.separatorStyle = .none
        table.tableFooterView = UIView()
        table.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 220, right: 0)
        table.isHidden = true
        return table
    }()
    
    lazy var searchButton: MTSearchFriendListHeaderView = {
        let s = MTSearchFriendListHeaderView()
        s.isHidden = true
        s.delegate = self
        return s
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "添加好友"
        view.addSubview(searchButton)
        view.addSubview(tableView)
        
        searchButton.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(StatusBarHeight + NavigationBarHeight + 10)
            make.height.equalTo(84)
        }
        
        tableView.snp.makeConstraints { (make) in
            //make.edges.equalToSuperview()
            make.bottom.left.right.equalToSuperview()
            make.top.equalTo(searchButton.snp.bottom)
        }

        searchController = SKSearchController(searchResultsController: nil)
        if #available(iOS 11.0, *) {
            navigationItem.searchController = searchController
            navigationItem.hidesSearchBarWhenScrolling = false // 这样子可以在进入页面的时候不隐藏
            searchController.obscuresBackgroundDuringPresentation = false
            searchController.hidesNavigationBarDuringPresentation = true // 编辑的时候隐藏导航栏
        } else {
            tableView.tableHeaderView = searchController.searchBar
        }
        
        setupSearchController()
        //getFriendList()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        setupSearchController()
    }
    
    /// 构建搜索控制器
    func setupSearchController() {
        searchController.placeholder = "觅颜号/手机号"
        searchController.customizeCancelButton = { button in
            button.setAttributedTitle(NSAttributedString(string: "取消", attributes: [.foregroundColor : UIColor.text.x1d1a1a, .font: PingFangSCMediumFont(14)]), for: .normal)
            //button.backgroundColor = UIColor(hex: 0xEE7F79)
            //button.layer.cornerRadius = 4
            //button.setTitleColor(.red, for: .normal)
        }
        
        //searchController.leftIcon = UIImage(named: "football")
        //searchController.leftIconColor =  UIColor.text.x1d1a1a
        //searchController.setRightBookmarkIcon(image: UIImage(named: "speaker"), color: UIColor(hex: 0xEE7F79), for: [.normal])
        searchController.setRightClearIcon(image: UIImage(named: "x"), color: UIColor(hex: 0xcdcdcd), for: [.normal])
        
        searchController.cursorColor = UIColor(hex: 0x333333)
        searchController.textFieldTextColor = UIColor.text.x9b9b9b
        searchController.textFieldFont = PingFangSCMediumFont(14)
        searchController.hideBorderLines = true
        searchController.textFieldBackgroundColor = UIColor(hex: 0xFFFFFF)
        
        searchController.textFieldBorderColor = UIColor(hex: 0xe6e6e6).cgColor
        searchController.textFieldBorderWidth = 1
        searchController.textFieldCornerRadius = 4
        searchController.removeBgView()
        
        searchController.searchTextDidChange = { [weak self] searchBar, text in
            //debugPrint("Keyword: \(text)")
            guard let weakSelf = self else { return }
            weakSelf.userMTorPhoneNumber = text
            
            weakSelf.searchButton.isHidden = text == "" ? true : false
            weakSelf.tableView.isHidden = text == "" ? true : false
            DispatchQueue.main.async {
                weakSelf.searchButton.snp.updateConstraints { (make) in
                    make.height.equalTo(text == "" ? 0 : 64)
                }
            }
            
            /// 筛选好友列表
            if text != "" {
                //userFriendList.count
                weakSelf.result.removeAll()
                DispatchQueue.main.async {
                    weakSelf.tableView.reloadData()
                }
            }
            
            weakSelf.searchButton.setSearchTitlt(title: text)
        }
        
        searchController.searchButtonClickHandler = { [weak self] searchBar in
            //guard let userName = searchBar.text else { return }
            guard let weakSelf = self else { return }
            weakSelf.searchUserFromDataBase(searchText: weakSelf.userMTorPhoneNumber)
        }
        
        searchController.searchBarCancelButtonClickHandler = { searchBar in
            self.navigationController?.dismiss(animated: true, completion: nil)
            self.navigationController?.popViewController(animated: true)
        }
        
        DispatchQueue.main.async {
            self.searchController.searchBar.becomeFirstResponder()
            if #available(iOS 13.0, *) {
                self.searchController.searchBar.searchTextField.becomeFirstResponder()
            } else {
                // Fallback on earlier versions
            }
        }
    }
    //UserCenterApiTool
    
    /// 搜索好友
    /// - Parameter searchText: 用户名 / 手机号
    private func searchUserFromDataBase(searchText: String) {
        if searchText.isEmpty {
            return
        }
        if searchText == JMSGUser.myInfo().username {
            MBProgressHUD_JChat.show(text: "不能添加自己为好友", view: self.view, 1)
            return
        }
        
        if let uid = Int(string: searchText), uid == UserCenter.default.id {
            MBProgressHUD_JChat.show(text: "不能添加自己为好友", view: self.view, 1)
            return
        }
        UserCenterApiTool.search(provider: userProvider, requestParam: ["search" : searchText], complete: { [weak self] (model) in
            guard let weakSelf = self else { return }
            if let m = model, m.code == 200 {
                if let count = m.result?.count {
                    weakSelf.updateUI(minHeight: count != 0)
                    if let muser = m.result?.first, count > 0 {
                        DispatchQueue.main.async {
                            let r: MTSearchFriendResultViewController = MTSearchFriendResultViewController()
                            //r.user = self.user
                            r.userModel = muser
                            weakSelf.navigationController?.pushViewController(r, animated: true)                            
                        }
                    } else {
                        MBProgressHUD_JChat.show(text: "未搜索到该用户", view: weakSelf.view)
                    }
                }
//                DispatchQueue.main.async {
//                    weakSelf.tableView.reloadData()
//                }
            } else {
                MBProgressHUD_JChat.show(text: "未搜索到该用户", view: weakSelf.view)
            }
        }) { (error) in
            let s = error
        }
        
    }
    
    private func updateUI(minHeight: Bool) {
        searchButton.snp.updateConstraints { (make) in
            make.height.equalTo(minHeight ? 0 : 84)
        }
        searchButton.isHidden = minHeight
    }
    
    private func seeachUserFromJChat(searchText: String) {
        if searchText.isEmpty {
            return
        }
        
        if searchText.count <= 4 {
            MBProgressHUD_JChat.show(text: "觅颜号 / 手机号过短", view: self.view, 2)
            return
        }
        
        MBProgressHUD_JChat.showMessage(message: "查找中", toView: self.view)
        JMSGUser.userInfoArray(withUsernameArray: [searchText]) { (result, error) in
            MBProgressHUD_JChat.hide(forView: self.view, animated: true)
            if error == nil {
                let users = result as! [JMSGUser]
                let user = users.first
                self.user = user
                if (user?.isFriend)! || (user?.isEqual(to: JMSGUser.myInfo()))! {
                    //self.addButton.isHidden = true
                    MBProgressHUD_JChat.show(text: "不能添加自己为好友", view: self.view, 2)
                    return
                } else {
                    let r: MTSearchFriendResultViewController = MTSearchFriendResultViewController()
                    //r.user = self.user
                    if let muser = self.result.first {
                        r.userModel = muser
                    }
                    self.navigationController?.pushViewController(r, animated: true)
                }
            } else {
                if let er = error as NSError?, er.code == 863001 {
                    MBProgressHUD_JChat.show(text: "觅颜号 / 手机号不合法", view: self.view, 2)
                } else {
                    MBProgressHUD_JChat.show(text: "未搜索到该用户", view: self.view, 2)
                }
            }
        }
    }
}

/// 搜索IM好友列表业务
extension MTSearchAddFriendViewController {
    /// 获取好友列表
    private func getFriendList() {
        
        JMSGFriendManager.getFriendList {[weak self] (result, error) in
            guard let weakSelf = self else { return }
            if let users = result as? [JMSGUser] {
                weakSelf.userFriendList = users
                weakSelf.tableView.reloadData()
            }
        }
        
    }
    
}


extension MTSearchAddFriendViewController {
    
    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
        return [.backgroundStyleColor, .backgroundStyleOpaque, .showShadowImage]
    }
}

extension MTSearchAddFriendViewController: MTSearchFriendListHeaderViewDelegate {
    func didTapSearchFriendButton() {
        searchUserFromDataBase(searchText: self.userMTorPhoneNumber)
//        if self.userMTorPhoneNumber.isEmpty || self.userMTorPhoneNumber == "" {
//            return
//        }
//
//        if self.userMTorPhoneNumber.count <= 4 {
//            MBProgressHUD_JChat.show(text: "觅颜号 / 手机号过短", view: self.view, 2)
//            return
//        }
//
//        MBProgressHUD_JChat.showMessage(message: "查找中", toView: self.view)
//        JMSGUser.userInfoArray(withUsernameArray: [self.userMTorPhoneNumber]) { (result, error) in
//            MBProgressHUD_JChat.hide(forView: self.view, animated: true)
//            if error == nil {
//                let users = result as! [JMSGUser]
//                let user = users.first
//                self.user = user
//                if (user?.isFriend)! || (user?.isEqual(to: JMSGUser.myInfo()))! {
//                    //self.addButton.isHidden = true
//                    MBProgressHUD_JChat.show(text: "不能添加自己为好友", view: self.view, 2)
//                    return
//                } else {
//                    let r: MTSearchFriendResultViewController = MTSearchFriendResultViewController()
//                    r.user = self.user
//                    self.navigationController?.pushViewController(r, animated: true)
//                }
//            } else {
//                if let er = error as NSError?, er.code == 863001 {
//                    MBProgressHUD_JChat.show(text: "觅颜号 / 手机号不合法", view: self.view, 2)
//                } else {
//                    MBProgressHUD_JChat.show(text: "未搜索到该用户", view: self.view, 2)
//
//                }
//            }
//        }
    }
}
